// 检查jQuery是否加载
if (typeof $ === 'undefined') {
    console.error('jQuery未加载，请检查jQuery引用');
}

// 全局Ajax配置
$(document).ajaxSend(function(event, xhr, options) {
    const token = localStorage.getItem("userToken");
    if (token) {
        xhr.setRequestHeader("user_token", token);
    }
    // 显示全局加载指示器
    if (!$('.global-loading').length) {
        $('body').append('<div class="global-loading">处理中...</div>');
    }
});

$(document).ajaxComplete(function(event, xhr, options) {
    // 隐藏全局加载指示器
    $('.global-loading').remove();
});

$(document).ajaxError(function(event, xhr, options, exc) {
    $('.global-loading').remove();
    if (xhr.status == 401) {
        showMessage("登录已过期，请重新登录", "error");
        setTimeout(() => {
            location.href = "blog_login.html";
        }, 1500);
    } else if (xhr.status >= 500) {
        showMessage("服务器内部错误，请稍后重试", "error");
    } else if (xhr.status === 0) {
        showMessage("网络连接失败，请检查网络", "error");
    }
});

function getUserInfo(url) {
    $.ajax({
        type: "get",
        url: url,
        success: function(result) {
            if (result != null && result.code && result.code.toString() === "SUCCESS" && result.data != null) {
                const userInfo = result.data;
                $(".left .card h3").text(userInfo.username || '用户');
                if (userInfo.githubUrl) {
                    $(".left .card a").attr("href", userInfo.githubUrl).show();
                } else {
                    $(".left .card a").hide();
                }
            } else {
                console.warn("获取用户信息失败:", result?.errMsg || '未知错误');
            }
        },
        error: function(xhr, status, error) {
            console.error("获取用户信息失败:", error);
            // 不显示错误信息，避免干扰用户体验
        }
    });
}

function logout() {
    showConfirm("确定要注销吗？", function() {
        localStorage.removeItem("userToken");
        localStorage.removeItem("loginUserId");
        showMessage("注销成功", "success");
        setTimeout(() => {
            location.href = "blog_login.html";
        }, 1000);
    });
}

// 通用的显示加载状态函数
function showLoading(buttonSelector, loadingText) {
    const $button = $(buttonSelector);
    $button.prop('disabled', true)
           .data('original-text', $button.text())
           .html('<span class="loading-spinner"></span>' + (loadingText || '处理中...'));
}

// 通用的隐藏加载状态函数
function hideLoading(buttonSelector) {
    const $button = $(buttonSelector);
    $button.prop('disabled', false)
           .text($button.data('original-text') || '提交');
}

// 通用的ajax错误处理函数
function handleAjaxError(xhr, defaultMessage) {
    let message = defaultMessage || "操作失败，请重试";
    if (xhr.responseJSON && xhr.responseJSON.errMsg) {
        message = xhr.responseJSON.errMsg;
    } else if (xhr.status === 0) {
        message = "网络连接失败，请检查网络";
    } else if (xhr.status >= 500) {
        message = "服务器内部错误，请稍后重试";
    }
    showMessage(message, "error");
}

// 美化的消息提示函数
function showMessage(message, type = 'info', duration = 3000) {
    const messageId = 'message-' + Date.now();
    const messageHtml = `
        <div id="${messageId}" class="custom-message custom-message-${type}">
            <span class="message-icon"></span>
            <span class="message-text">${message}</span>
        </div>
    `;
    
    $('body').append(messageHtml);
    
    // 动画显示
    setTimeout(() => {
        $(`#${messageId}`).addClass('show');
    }, 10);
    
    // 自动隐藏
    setTimeout(() => {
        $(`#${messageId}`).removeClass('show');
        setTimeout(() => {
            $(`#${messageId}`).remove();
        }, 300);
    }, duration);
}

// 美化的确认对话框
function showConfirm(message, onConfirm, onCancel) {
    const confirmId = 'confirm-' + Date.now();
    const confirmHtml = `
        <div id="${confirmId}" class="custom-confirm-overlay">
            <div class="custom-confirm">
                <div class="confirm-icon">?</div>
                <div class="confirm-message">${message}</div>
                <div class="confirm-buttons">
                    <button class="confirm-btn cancel-btn">取消</button>
                    <button class="confirm-btn confirm-btn-primary">确定</button>
                </div>
            </div>
        </div>
    `;
    
    $('body').append(confirmHtml);
    
    // 绑定事件
    $(`#${confirmId} .cancel-btn`).click(function() {
        $(`#${confirmId}`).remove();
        if (onCancel) onCancel();
    });
    
    $(`#${confirmId} .confirm-btn-primary`).click(function() {
        $(`#${confirmId}`).remove();
        if (onConfirm) onConfirm();
    });
    
    // 点击遮罩关闭
    $(`#${confirmId}`).click(function(e) {
        if (e.target.id === confirmId) {
            $(`#${confirmId}`).remove();
            if (onCancel) onCancel();
        }
    });
}

// 格式化日期函数
function formatDate(dateString) {
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}`;
}

// 截取文本函数
function truncateText(text, maxLength = 150) {
    if (!text) return '';
    return text.length > maxLength ? text.substring(0, maxLength) + '...' : text;
}

// 页面加载完成后的初始化
$(document).ready(function() {
    // 检查是否需要登录
    if (location.pathname.includes('blog_list.html') || 
        location.pathname.includes('blog_detail.html') || 
        location.pathname.includes('blog_edit.html') || 
        location.pathname.includes('blog_update.html')) {
        const token = localStorage.getItem('userToken');
        if (!token) {
            showMessage('请先登录', 'warning');
            setTimeout(() => {
                location.href = 'blog_login.html';
            }, 1500);
        }
    }
    
    // 初始化暗黑模式
    initDarkMode();
    
    // 添加返回顶部按钮
    addBackToTopButton();
    
    // 添加页面加载进度条
    showPageLoadProgress();
});

// 暗黑模式功能
function initDarkMode() {
    const isDarkMode = localStorage.getItem('darkMode') === 'true';
    if (isDarkMode) {
        document.body.classList.add('dark-mode');
    }
    
    // 在导航栏添加暗黑模式切换按钮
    if ($('.nav').length > 0) {
        const darkModeToggle = $(`
            <button class="dark-mode-toggle" onclick="toggleDarkMode()" title="切换暗黑模式">
                <span class="moon-icon">🌙</span>
                <span class="sun-icon">☀️</span>
            </button>
        `);
        $('.nav').append(darkModeToggle);
    }
}

function toggleDarkMode() {
    const isDarkMode = document.body.classList.toggle('dark-mode');
    localStorage.setItem('darkMode', isDarkMode);
    showMessage(isDarkMode ? '已切换到暗黑模式' : '已切换到明亮模式', 'info', 1500);
}

// 返回顶部按钮
function addBackToTopButton() {
    const backToTopHtml = `
        <button id="backToTop" class="back-to-top" onclick="scrollToTop()" title="返回顶部">
            ↑
        </button>
    `;
    $('body').append(backToTopHtml);
    
    // 监听滚动事件
    $(window).scroll(function() {
        if ($(this).scrollTop() > 300) {
            $('#backToTop').addClass('show');
        } else {
            $('#backToTop').removeClass('show');
        }
    });
}

function scrollToTop() {
    $('html, body').animate({scrollTop: 0}, 800);
}

// 页面加载进度条
function showPageLoadProgress() {
    const progressHtml = '<div id="page-progress" class="page-progress"></div>';
    $('body').prepend(progressHtml);
    
    setTimeout(() => {
        $('#page-progress').addClass('complete');
        setTimeout(() => {
            $('#page-progress').remove();
        }, 500);
    }, 200);
}